/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.namabank.servlet.helpdesk;

import com.namabank.db.GlobalHibernate;
import com.namabank.helpdesk.dbobj.HDTB_TICKET;
import com.namabank.helpdesk.model.RoleModel;
import com.namabank.servlet.BaseServlet;
import com.namabank.servlet.EvaluateParam;
import com.namabank.util.TemplateFile;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONObject;

/**
 *
 * @author Gostep
 */
public class OneTicketServlet extends BaseServlet {

    public static final String PARAM_EDIT_REQUESTER_NAME = "editRequester";
    public static final String PARAM_REQUESTER_NAME_NAME = "requesterName";
    public static final String PARAM_REQUESTER_DESK_PHONE_NAME = "requesterDeskPhone";
    public static final String PARAM_REQUESTER_CELL_PHONE_NAME = "requesterCellPhone";
    public static final String PARAM_REQUESTER_EMAIL_NAME = "requesterEmail";
    public static final String PARAM_REQUESTER_DEPT_NAME = "requesterDept";
    public static final String PARAM_REQUESTER_JOB_TITLE_NAME = "requesterJobTitle";

    public static final String PARAM_REQUEST_TITLE = "requestTitle";
    public static final String PARAM_REQUEST_CONTENT = "requestContent";
    public static final String PARAM_REQUEST_MODE_ID = "modeId";
    public static final String PARAM_REQUEST_STATUS_ID = "statusId";
    public static final String PARAM_REQUEST_URGENCY = "urgency";
    public static final String PARAM_REQUEST_PRIORITY_ID = "priorityId";
    public static final String PARAM_REQUEST_CATEGORY_ID = "cateId";
    public static final String PARAM_REQUEST_ACTION_ID = "actionId";

    private Logger logger = Logger.getLogger(OneTicketServlet.class);

    @Override
    protected void mainProcess(EvaluateParam evalparam) {
        String state = evalparam.getTrimmedNotEmptyParameter("state");
        if ("create_new".equals(state)) {
            initCreateNew(evalparam);
        } else if ("submit_ticket".equals(state)) {
            submitTicket(evalparam);
        } else if ("get_action_of_cate".equals(state)) {
            getActionOfCategory(evalparam);
        }
    }

    /**
     * Khởi tạo màn hình nhập ticket, trả về client đoạn HTML render giao diện
     * nhập ticket
     * @param evalparam
     */
    void initCreateNew(EvaluateParam evalparam) {
        if (!evalparam.getUserModel().hasRole(RoleModel.TICKET_INPUT)) {
            evalparam.setResponseError("Bạn không có quyền nhập yêu cầu");
            return;
        }
        HashMap<String, Object> params = evalparam.genParamsVariable();

        if (!evalparam.getUserModel().hasRole(RoleModel.HELPDESK_INPUT) && evalparam.getUserModel().getSmtbUserObj() != null
                && evalparam.getUserModel().getListActiveUserDeptObj().size() > 0) {
            params.put(PARAM_EDIT_REQUESTER_NAME, "readonly");
            params.put(PARAM_REQUESTER_NAME_NAME, evalparam.getUserModel().getSmtbUserObj().getUSER_NAME());
            params.put(PARAM_REQUESTER_DESK_PHONE_NAME, evalparam.getUserModel().getSmtbUserObj().getDESK_PHONE());
            params.put(PARAM_REQUESTER_CELL_PHONE_NAME, evalparam.getUserModel().getSmtbUserObj().getCELL_PHONE());
            params.put(PARAM_REQUESTER_EMAIL_NAME, evalparam.getUserModel().getSmtbUserObj().getEMAIL_ADDRESS());
            params.put(PARAM_REQUESTER_DEPT_NAME, evalparam.getUserModel().getListActiveUserDeptObj().get(0).getDEPT_ID());
            params.put(PARAM_REQUESTER_JOB_TITLE_NAME, evalparam.getUserModel().getListActiveUserDeptObj().get(0).getJOBT_ID());
        }

        /**
         * Lấy danh sách Category có RECORD_STAT là O
         * gán vào JSONArray, mỗi phần tử là một JSONObject gồm: 
         * <i>cateId</i>: mã category
         * <i>cateName</i>: tên category
         * <i>cateDesc</i>: mô tả category
         * <i>cateParentId</i>: mã của category cha
         */
        JSONArray listCategory = new JSONArray();
        String qry = "select CATEGORY_ID, CATEGORY_NAME, CATEGORY_DESC, PARENT_CATEGORY_ID from HDTB_CATEGORY where RECORD_STAT = 'O'";
        List lst = GlobalHibernate.openSession().createQuery(qry).list();
        for (int i = 0; i < lst.size(); i++) {
            JSONObject json = new JSONObject();
            Object[] objs = (Object[]) lst.get(i);
            try {
                json.put("cateId", objs[0]);
                json.put("cateName", StringEscapeUtils.escapeHtml((String) objs[1]));
                json.put("cateDesc", (String) objs[2]);
                json.put("cateParentId", objs[3]);
                listCategory.put(json);
            } catch (Exception ex) {
                logger.info("Loi khi query danh sach category, bo qua record " + objs[0], ex);
                continue;
            }
        }
        params.put("lstCategory", listCategory);


        TemplateFile tp = new TemplateFile();
        String contentPanel = tp.readTemplateHTML(evalparam.getUserModel().getSmtbUserObj().getUSE_TEMPLATE(), "create_new_ticket");
        contentPanel = tp.replaceByParams(contentPanel, params);
        evalparam.setResponseHTML(contentPanel, "one_ticket", null);
    }

    /**
     * Trả về client danh sách Action có RECORD_STAT là O
     * gán vào JSONArray, mỗi phần tử là một JSONObject gồm:
     * <i>cateId</i>: mã category
     * <i>cateName</i>: tên category
     * <i>cateDesc</i>: mô tả category
     * <i>cateParentId</i>: mã của category cha
     */
    void getActionOfCategory(EvaluateParam evalparam) {
        String cateId = evalparam.getTrimmedNotEmptyParameter("cateId");
        if (cateId == null) {
            evalparam.setResponseJSON("[]", null);
            return;
        }
        JSONArray listAction = new JSONArray();
        String qry = "select ac.ACTION_ID, ac.ACTION_NAME, ac.ACTION_DESC"
                + " from HDTB_ACTION ac, HDTB_CATEGORY_ACTION mp"
                + " where mp.CATEGORY_ID = '" + StringEscapeUtils.escapeSql(cateId) + "'"
                + " and ac.ACTION_ID = mp.ACTION_ID"
                + " and ac.RECORD_STAT = 'O' and mp.RECORD_STAT = 'O'";
        List<Object[]> lst = GlobalHibernate.openSession().createQuery(qry).list();
        for (int i = 0; i < lst.size(); i++) {
            Object[] objs = lst.get(i);
            JSONObject json = new JSONObject();
            try {
                json.put("actionId", objs[0]);
                json.put("actionName", StringEscapeUtils.escapeHtml((String) objs[1]));
                json.put("actionDesc", (String) objs[2]);
                listAction.put(json);
            } catch (Exception ex) {
                logger.info("Loi khi query danh sach HDTB_CATEGORY_ACTION, bo qua record " + objs[0], ex);
                continue;
            }
        }
        evalparam.setResponseJSON(listAction.toString(), null);
    }

    /**
     * 
     * @param evalparam
     */
    void submitTicket(EvaluateParam evalparam) {
        String requesterId = evalparam.getUserId();
        String requesterDept = evalparam.getTrimmedNotEmptyParameter(PARAM_REQUESTER_DEPT_NAME);

        String requestTitle = evalparam.getTrimmedNotEmptyParameter(PARAM_REQUEST_TITLE);
        String requestContent = evalparam.getTrimmedNotEmptyParameter(PARAM_REQUEST_CONTENT);
        String requestModeId = evalparam.getTrimmedNotEmptyParameter(PARAM_REQUEST_MODE_ID);
        String requestStatusId = evalparam.getTrimmedNotEmptyParameter(PARAM_REQUEST_STATUS_ID);
        String requestUrgency = evalparam.getTrimmedNotEmptyParameter(PARAM_REQUEST_URGENCY);
        String requestPriorityId = evalparam.getTrimmedNotEmptyParameter(PARAM_REQUEST_PRIORITY_ID);
        String requestCategoryId = evalparam.getTrimmedNotEmptyParameter(PARAM_REQUEST_CATEGORY_ID);
        String requestActionId = evalparam.getTrimmedNotEmptyParameter(PARAM_REQUEST_ACTION_ID);

        JSONArray emptyList = new JSONArray();
        if(requestTitle == null) emptyList.put(PARAM_REQUEST_TITLE);
        if(requestContent == null) emptyList.put(PARAM_REQUEST_CONTENT);
        if(requestPriorityId == null) emptyList.put(PARAM_REQUEST_PRIORITY_ID);
        if(requestCategoryId == null) emptyList.put(PARAM_REQUEST_CATEGORY_ID);
        if(requestActionId == null) emptyList.put(PARAM_REQUEST_ACTION_ID);

        if(emptyList.length() > 0){
            evalparam.setResponseJSON(emptyList.toString(), "submit_ticket");
            return;
        }

        Double dUrgency = Double.parseDouble(requestUrgency);
        HDTB_TICKET newTicket = new HDTB_TICKET();

        // gán gia trị cho ticket mới
        newTicket.setCATEGORY_ID(requestCategoryId);
        newTicket.setDEPT_REQUEST(requesterDept);
        newTicket.setINSERT_STAMP(new Date());
        newTicket.setMODE_ID(requestModeId);
        newTicket.setPRIORITY_ID(requestPriorityId);
        newTicket.setTICKET_DESC(requestContent);
        newTicket.setTICKET_TITLE(requestTitle);
        newTicket.setURGENCY(dUrgency);
        newTicket.setUSER_REQUEST(requesterId);
        newTicket.setUSER_SUBMIT(requesterId);
        newTicket.setSTATUS_ID(requestStatusId);
        newTicket.setACTION_ID(requestActionId);
    }
}
